//
//  SYSelectStuViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/7/15.
//  Copyright © 2016年 zz. All rights reserved.
//
#define headWidth 38    //头像的宽度
#define LOGOSTR @"/logo/logo_02.png"

#import "SYSelectStuViewController.h"
#import "SYContractsCell.h"
#import "StudentsModel.h"
#import "OneLabelTableViewCell.h"
#import "UIView+Frame.h"

#import "ChineseToPinyin.h"


#import "AssignStuHomeWorkViewController.h"
#import "PushStuNotiViewController.h"

@interface SYSelectStuViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong) UITableView *table;
@property(nonatomic,strong) UITableView *searchTable;

@property (strong, nonatomic) UIView *footerView;
@property (strong, nonatomic) UIScrollView *footerScrollView;
@property(nonatomic,strong) UITextField *pldTextField; //选择联系人的pldTextField
@property(nonatomic,strong) UILabel *bgLabel; //没有内容时候的提示问题

@property(nonatomic,strong) NSMutableArray *dataArr;
@property(nonatomic,strong) NSMutableArray *selectedArr; //存放已选择学生的数组
@property(nonatomic,strong) NSMutableArray *searchArr;   //存放搜索到的学生数组

@end

@implementation SYSelectStuViewController{
    
    BOOL selectAll; //是否全选
    
    BOOL noSelectAll; //反选
    
    CGFloat oriWidth;  //选择联系人的宽度
    
    UIImageView *textImageView;  //textField的左边图片
   
    
    UIImageView *noStuImageView; //没有学生时候的背景图片
}

#pragma mark -getter方法
-(NSMutableArray *)dataArr{
    
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}

-(NSMutableArray *)selectedArr{
    
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    
    return _selectedArr;
}

-(NSMutableArray *)searchArr{
    
    if (_searchArr == nil) {
        
        _searchArr = [NSMutableArray array];
    }
    
    return _searchArr;
}

-(UIView *)footerView{
    
    if (!_footerView) {
        
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 60)];
        _footerView.backgroundColor = [UIColor whiteColor];
        _footerView.userInteractionEnabled = YES;
        
        CGFloat width = SCREENWIDTH;
        
        
        
        int num; //联系人头最多显示个数，5，6，7
        
        if (width == 320) {
            
            num = 5;
        }else if (width == 375){
            
            num = 6;
        }else {
            
            num = 7;
        }
        
        CGFloat scrollW =  12 + 6 * num + num * headWidth;
        
        oriWidth = scrollW;
        
        _footerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, scrollW, 60)];
        _footerScrollView.bounces = NO;
        _footerScrollView.delegate = self;
        _footerScrollView.backgroundColor = [UIColor whiteColor];
        [_footerView addSubview:_footerScrollView];
        
        _pldTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, VIEW_WIDTH - 40, 60)];
        
        
        textImageView = [[UIImageView alloc] init];

        textImageView.image = [UIImage imageNamed:@"serch_friends_"];
        textImageView.frame = CGRectMake(0, 0, 20, 20);
        textImageView.width += 10;
        textImageView.contentMode = UIViewContentModeCenter;
        
        _pldTextField.leftView = textImageView;
        _pldTextField.leftViewMode = UITextFieldViewModeAlways;
        _pldTextField.borderStyle = UITextBorderStyleNone;
        //_pldTextField.placeholder = @"至少选择一名联系人";
        _pldTextField.placeholder = @"搜索";
        _pldTextField.textAlignment = NSTextAlignmentCenter;
        _pldTextField.textAlignment = NSTextAlignmentLeft;
        _pldTextField.font = [UIFont systemFontOfSize:14];
        _pldTextField.delegate = self;
        _pldTextField.enabled = YES;
        [_pldTextField addTarget:self action:@selector(searchTextChange:) forControlEvents:UIControlEventEditingChanged];
        _pldTextField.backgroundColor = [UIColor whiteColor];
        
        [_footerView addSubview:_pldTextField];

    }
    return _footerView;
}

-(UITableView *)table{
    
    if (!_table) {
    
        
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.footerView.frame), VIEW_WIDTH, VIEW_HEIGHT - 60 - 64)style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.tableFooterView = [[UIView alloc] init];
        _table.separatorStyle=UITableViewCellAccessoryNone;
        
        noStuImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no_achievement_"]];
        noStuImageView.center = CGPointMake(_table.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
        noStuImageView.hidden = YES;
        [self.view addSubview:noStuImageView];
        
        _searchTable = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.footerView.frame), VIEW_WIDTH, VIEW_HEIGHT - 60 - 64) style:UITableViewStylePlain];
        _searchTable.dataSource = self;
        _searchTable.delegate = self;
        
        _searchTable.tableFooterView = [[UIView alloc] init];
        _searchTable.hidden = YES;
        _searchTable.separatorStyle = UITableViewCellSelectionStyleNone;
        [self.view addSubview:_searchTable];
        
        _bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 152, SCREENWIDTH-60, 60)];
        _bgLabel.textAlignment=NSTextAlignmentCenter;
        
        _bgLabel.textColor=RGBCOLOR(151, 151, 151);
        _bgLabel.numberOfLines=2;
        _bgLabel.hidden = YES;
        [_searchTable addSubview:_bgLabel];
    }
    
    return _table;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureNav];
    
    [self configreUI];
    
    [self getStudentsData];
}


-(void)configureNav{
    
    self.navBar.nav_titleLabel.text = self.classTitle;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backBtn;
   
   self.navBar.rightButton.hidden = NO;
    [self.navBar.rightButton setTitleColor:RGBCOLOR(221, 221, 221) forState:UIControlStateNormal];
    self.navBar.rightButton.enabled = NO;
    self.navBar.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.navBar.rightButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
   self.navBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.navBar.rightButton setTitle:@"确定" forState:UIControlStateNormal];
   
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)configreUI{
    
    [self.view addSubview:self.footerView];
    
    [self.view addSubview:self.table];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark -UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == _table) {
        return 2;
    }else{
        return 1;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == _table) {
        
        if (section == 0) {
            return 1;
        }
        
        return _dataArr.count;
    }else{
        
        return self.searchArr.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _table) {
        
        if (indexPath.section == 0) {
            
            OneLabelTableViewCell *cell = [[OneLabelTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            
            if (selectAll) {
                cell.seletImage.image = [UIImage imageNamed:@"ok_choosefriends_"];
            }else{
                cell.seletImage.image = [UIImage imageNamed:@"no_choosefriends_"];
            }
            
            cell.label.text = @"全选";
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
        
            static NSString *headCellId = @"cellid";
            SYContractsCell *cell = [tableView dequeueReusableCellWithIdentifier:headCellId];
            
            if (cell == nil) {
                
                cell = [[SYContractsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:headCellId];
            }
            
            StudentsModel *model = [self.dataArr objectAtIndex:indexPath.row];
            
            cell.nameLabel.text = model.studentname;
            cell.nameLabel.font=[UIFont systemFontOfSize:15];
            NSString *name = model.studentname;
            
            if (name.length > 2) {
                name = [name substringFromIndex:name.length - 2];
            }
            
            NSString *logoStr = model.logo;
            
            
            if (logoStr.length == 0) {
                logoStr = @"/logo/logo_02.png";
            }
            
             if (![logoStr hasPrefix:@"http"] && logoStr){
                logoStr = [REQUESTIMAGEURL stringByAppendingString:logoStr];
            }
            
            [cell.headView.headImage sd_setImageWithURL:[NSURL URLWithString:logoStr]];
            cell.headView.namelabel.text = name;
            cell.headView.namelabel.font=[UIFont systemFontOfSize:14];
            cell.headView.flag = model.logotype == 1?YES:NO;
            
             if (model.flag == NO) {
             
                cell.selectimg.image=[UIImage imageNamed:@"no_choosefriends_"];
            }else{
                cell.selectimg.image=[UIImage imageNamed:@"ok_choosefriends_"];
            }

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }else{
        
        static NSString *cellid = @"selectcell";
        
        SYContractsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        
        if (cell == nil) {
            
            cell = [[SYContractsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        }
        
        StudentsModel *model = [self.searchArr objectAtIndex:indexPath.row];
        
        cell.nameLabel.text = model.studentname;
        
        NSString *name = model.studentname;
        
        if (name.length > 2) {
            name = [name substringFromIndex:name.length - 2];
        }
        
        NSString *logoStr = model.logo;
        
        
        if (logoStr.length == 0) {
            logoStr = @"/logo/logo_02.png";
        }
        
         if (![logoStr hasPrefix:@"http"] && logoStr) {
            logoStr = [REQUESTIMAGEURL stringByAppendingString:logoStr];
        }
        
        [cell.headView.headImage sd_setImageWithURL:[NSURL URLWithString:logoStr]];
        cell.headView.namelabel.text = name;
        cell.headView.flag = model.logotype == 1?YES:NO;
        
        if (model.flag == NO) {
            
            cell.selectimg.image=[UIImage imageNamed:@"no_choosefriends_"];
        }else{
            cell.selectimg.image=[UIImage imageNamed:@"ok_choosefriends_"];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
}

#pragma mark -UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _table) {
        
        
        if (indexPath.section == 0) {
            
            OneLabelTableViewCell *cell = [self.table cellForRowAtIndexPath:indexPath];
            
            if (selectAll) {  //点击全不选
                
                cell.seletImage.image = [UIImage imageNamed:@"no_choosefriends_"];
                [self.selectedArr removeAllObjects];
                

                for (int i = 0; i < self.dataArr.count; i++) {
                    
                    StudentsModel *sModel = [self.dataArr objectAtIndex:i];
                    
                    sModel.flag = NO;
                    [self.dataArr replaceObjectAtIndex:i withObject:sModel];
                }



                
            }else{     //点击全选
                
                cell.seletImage.image = [UIImage imageNamed:@"ok_choosefriends_"];
                [self.selectedArr removeAllObjects];
                [self.selectedArr addObjectsFromArray:self.dataArr];
                
                for (int i = 0; i < self.dataArr.count; i++) {
                    
                    StudentsModel *sModel = [self.dataArr objectAtIndex:i];
                    
                    sModel.flag = YES;
                    [self.dataArr replaceObjectAtIndex:i withObject:sModel];
                }
                

            }
            
            selectAll = !selectAll;
            [self refreshTopView];
            [self.table reloadData];
            
        }else{
        
            
            StudentsModel *model = [self.dataArr objectAtIndex:indexPath.row];
            
            if (model.flag) {  //取消
                

                [self.selectedArr removeObject:model];
                
                selectAll = NO;
                
            }else{
                
                
                [self.selectedArr addObject:model];
                if (self.selectedArr.count == self.dataArr.count) {
                    
                    selectAll = YES;
                }
                
            }
            model.flag = !model.flag;
            [self.dataArr replaceObjectAtIndex:indexPath.row withObject:model];
            
            //刷新顶部视图
            [self refreshTopView];
            [self.table reloadData];
        }
        
    }else{  //搜索出来的cell点击
        
        StudentsModel *model = [self.searchArr objectAtIndex:indexPath.row];
        
        
        
        if (model.flag) {
            
            for (StudentsModel *model1 in self.selectedArr) {
                
                if (model1.studentid == model.studentid) {
                    
                    
                    [self.selectedArr removeObject:model1];
                    break;
                }
            }
            

            selectAll = NO;

        }else{
            
            [self.selectedArr addObject:model];
            
            if (self.selectedArr.count == self.dataArr.count) {
                
                selectAll = YES;
            }
        }
        
        model.flag = !model.flag;
        
        [self.dataArr replaceObjectAtIndex:model.index withObject:model];
        
        [self refreshTopView];
        [self.table reloadData];
        
        _table.hidden = NO;
        _searchTable.hidden = YES;
        self.pldTextField.text = @"";
        [self.pldTextField endEditing:YES];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 10)];
    view.backgroundColor = RGBCOLOR(239, 239, 244);
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.5)];
    line1.backgroundColor = RGBCOLOR(199, 199, 204);
    [view addSubview:line1];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 9.5, VIEW_WIDTH, 0.5)];
    line2.backgroundColor = RGBCOLOR(199, 199, 204);
    [view addSubview:line2];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

#pragma mark -加载班级学生数据
-(void)getStudentsData{
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@"api_classstudent_list" forKey:@"Method"];
    
    if (_classid) {
        
        [param setObject:_classid forKey:@"classid"];

    }
    [param setObject:@"1" forKey:@"pageon"];
    [param setObject:@"10000" forKey:@"pagesize"];
    
    [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if (arr.count == 0) {
            
            self->noStuImageView.hidden = NO;
            [self.table reloadData];
            self.table.hidden = YES;
            self.footerView.hidden = YES;
            return;
        }
        
        self.footerView.hidden = NO;
        self.table.hidden = NO;
        self ->noStuImageView.hidden = YES;
        
        self.dataArr = [StudentsModel mj_objectArrayWithKeyValuesArray:arr];
        
        [self.dataArr sortedArrayUsingComparator:^NSComparisonResult(StudentsModel *obj1, StudentsModel *obj2) {
            
            NSString *firstLetter1 = [ChineseToPinyin pinyinFromChineseString:obj1.studentname];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
            NSString *firstLetter2 = [ChineseToPinyin pinyinFromChineseString:obj2.studentname];
            firstLetter2 = [[firstLetter2 substringFromIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        //存入数据库以便查询
        [fmdbTool saveStudentsInfoWithArray:self.dataArr];
        
        [self.table reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
}

#pragma mark -searchTextChange
-(void)searchTextChange:(UITextField *)sender{
    
    if ([sender.text isEqualToString:@""]) {
        
        _table.hidden = NO;
        _searchTable.hidden = YES;
        [sender endEditing:YES];
        
    }else{
    
        _table.hidden = YES;
        _searchTable.hidden = NO;
        

        [self.searchArr removeAllObjects];
        NSArray *arr = (NSArray *)[fmdbTool searchStudentsWithNameStr:sender.text];
        [self.searchArr addObjectsFromArray:arr];
        
        for (int j = 0;j < self.dataArr.count;j++) {
            
            StudentsModel *model1 = [self.dataArr objectAtIndex:j];
            
            for (int i = 0;i < self.searchArr.count;i++) {
                
                StudentsModel *model2 = [self.searchArr objectAtIndex:i];
                
                if (model1.studentid == model2.studentid) {
                    
                    model2.flag = model1.flag;
                    model2.index = j;
                    
                    [self.searchArr replaceObjectAtIndex:i withObject:model2];
                    break;
                }
            }
        }
        
        [self.searchTable reloadData];
    }

}

#pragma mark -确定按钮点击事件
-(void)sendAction:(UIButton *)sender{
    
    if (_selectedArr.count == 0) {
        return;
    }
    
    AppDelegate *appdelegate=CONSTAPPDELEGATE;
    
    NSDictionary *dict = @{@"re_data": _selectedArr,@"type":@"2"};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"senderNotification" object:nil userInfo:dict];
    
    for(UIViewController *vc in self.navigationController.childViewControllers)
    {
        if ([appdelegate.isNotOrHome isEqualToString:@"zy"]) {
            if ([vc isKindOfClass:[AssignStuHomeWorkViewController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                break;
            }
        }else if ([appdelegate.isNotOrHome isEqualToString:@"tz"])
        {
            if ([vc isKindOfClass:[PushStuNotiViewController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                break;
            }
        }
    }
}

#pragma mark -刷新顶部表格
-(void)refreshTopView{
    
    [self.footerScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat count =  self.selectedArr.count;
    
    /*判断有选择的人就隐藏搜索框的view*/
    if (count != 0) {
        
        _pldTextField.leftView = nil;
        
    }else{
        
        _pldTextField.leftView = textImageView;
    }
    
    _footerScrollView.contentSize = CGSizeMake((38 + 6) * count + 12, 0);
    
    CGFloat x = _footerScrollView.contentOffset.x;
    
    _footerScrollView.contentOffset = CGPointMake(x, 0);
    
    //改变导航条右侧按钮
    NSString *btnTitle;
    if (count > 0) {
        
        btnTitle = [NSString stringWithFormat:@"确定(%d)",(int)count];
        [self.navBar.rightButton setTitleColor:RGBCOLOR(59, 59, 59) forState:UIControlStateNormal];
        self.navBar.rightButton.enabled = YES;
    }else{
        btnTitle = @"确定";
        [self.navBar.rightButton setTitleColor:RGBCOLOR(221, 221, 221) forState:UIControlStateNormal];
        self.navBar.rightButton.enabled = NO;
    }
    
    [self.navBar.rightButton setTitle:btnTitle forState:UIControlStateNormal];
    
    //改变搜索框的位置
    CGRect fieldRect = _pldTextField.frame;
    fieldRect.origin.x = _footerScrollView.contentSize.width + 6;
    _pldTextField.frame = fieldRect;
    
    for (int i = 0; i < count; i++) {
        
        StudentsModel *model = [self.selectedArr objectAtIndex:i];
        
        NSString *name = model.studentname;
        if (name.length > 2) {
            name = [name substringFromIndex:name.length - 2];
        }
        NSString *logo = model.logo;
        
        if (logo.length == 0) {
            logo = LOGOSTR;
        }
        
        if (logo && ![logo hasPrefix:@"http"]) {
            logo = [NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,logo];
        }
        
        XZHeaderImageView *headView = [[XZHeaderImageView alloc] initWithFrame:CGRectMake(12 +i *(38+6), 12, 38, 38)];
        [headView.headImage sd_setImageWithURL:[NSURL URLWithString:logo]];
        headView.namelabel.text = name;
        headView.namelabel.font = [UIFont systemFontOfSize:14];
        headView.flag = model.logotype == 1?YES:NO;
        
        [self.footerScrollView addSubview:headView];
        
        if (i == count - 1) {
            
            CGFloat maxX = CGRectGetMaxX(headView.frame) + 12;
            
            if (maxX > oriWidth) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    CGPoint size = self->_footerScrollView.contentOffset;
                    
                    size.x = maxX - self->oriWidth;
                    
                    self.footerScrollView.contentOffset = size;
                }];
            }
        }

    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    [self.pldTextField endEditing:YES];
}


@end
